package lib.hj.com.commonlib.manager;

import android.os.Environment;
import android.util.Log;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.builder.OkHttpRequestBuilder;
import com.zhy.http.okhttp.builder.PostStringBuilder;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import lib.hj.com.commonlib.bean.BaseBean;
import lib.hj.com.commonlib.utils.Callback;
import lib.hj.com.commonlib.utils.Constant;
import lib.hj.com.commonlib.utils.Req;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;

/**
 * Created by "丁永泽" on 2016/9/22.
 */

public class HttpManager {
    private static boolean isInit = false;

    public static  String  logFile = "";
    public static void getHttpData(Req req) {


        if (!isInit) {

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(15000L, TimeUnit.MILLISECONDS)
                    .readTimeout(15000L, TimeUnit.MILLISECONDS)
                    .build();

            OkHttpUtils.initClient(okHttpClient);
            isInit = true;
            try {
                logFile = getSDPath() + File.separator + "SAAPP" + File.separator + "log" + getNowDate() + ".txt";
                File file = new File(getSDPath() + File.separator + "SAAPP");
                if (!file.exists()) {
                    file.mkdirs();
                }
                File file1 = new File(logFile);
                if (!file1.exists()) {
                    try {
                        file1.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            } catch (Exception e) {

            }
            }

        OkHttpRequestBuilder builder = null;
        Map<String, String> map = req.parameter;

        String url = req.url;

        if (req.method == Constant.Method.GET || req.method == null) {
            GetBuilder getBuilder = OkHttpUtils
                    .get();

            //遍历map中的键

            if (map != null) {

                for (String key : map.keySet()) {


                    getBuilder.addParams(key, map.get(key).toString());


                }
            }

            builder = getBuilder;


        }
        if (req.method == Constant.Method.POST) {

            PostStringBuilder postStringBuilder = OkHttpUtils.postString();
            String data = "";
            if (map != null) {

                int i = 0;
                for (String key : map.keySet()) {


                    data += key + "=" + map.get(key);
                    i++;
                    if (0 < i && i < map.size()) {
                        data += "&";
                    }

                }
            }

            postStringBuilder.content(data);
            req.postData = data;
            postStringBuilder.mediaType(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"));
            builder = postStringBuilder;

        }

        builder.url(url);
        RequestCall requestCall = builder.build();
        requestCall.execute(new Callback(req));


    }

    public static void getHttpDataByOffline(Req req) {


        if (!isInit) {

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                    .readTimeout(10000L, TimeUnit.MILLISECONDS)
                    .build();
            OkHttpUtils.initClient(okHttpClient);
            isInit = true;
        }

        OkHttpRequestBuilder builder = null;
        String url = req.url;
        PostStringBuilder postStringBuilder = OkHttpUtils.postString();
        postStringBuilder.content(req.postData);
        postStringBuilder.mediaType(MediaType.parse("application/x-www-form-urlencoded; charset=gbk"));
        builder = postStringBuilder;
        builder.url(url);
        req.cls = BaseBean.class;
        RequestCall requestCall = builder.build();
        requestCall.execute(new Callback(req));
    }
    public static void  myLog(String title,String content) {

        try {
            HttpManager.saveCrashInfo2File(title, content);
            Log.e(title, content);
        } catch (Exception e) {

        }

    }

    /**
     * 保存错误信息到文件中
     *

     * @return  返回文件名称,便于将文件传送到服务器
     */
    public static String saveCrashInfo2File(String title, String content) {


        try {
            FileWriter fw = new  FileWriter( logFile ,  true );
            fw.append("\r\n" );
            fw.write(  title+"--->"+content);
            fw.append("\r\n" );  //写入换行
            fw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }

        return sdDir.toString();
    }

    /**
     * 获取现在时间
     *
     * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
     */
    public static String getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
}
